<?php

namespace app\admin\controller\csmwj;

use addons\csmwj\library\xcore\xcore\base\XcABackend;
use addons\csmwj\library\xcore\xcore\utils\XcRequestUtils;
use addons\csmwj\library\xcore\xcore\utils\XcAdminTabUtils;

/**
 * 工单
 *
 * @icon fa fa-circle-o
 */
class Paperstatistic extends XcABackend
{
    protected $noNeedLogin = '*';
    /**
     * Paper模型对象
     *
     * @var \app\admin\model\csmwj\Paper
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\csmwj\Paper();
        $this->view->assign("baseurl", $this->request->baseUrl());

        // csmwj:设置页面tabs
        $id = XcRequestUtils::param("id");
        XcAdminTabUtils::append_control_initialize('paper_statistic', $id, __CLASS__, $this->view);
    }


    public function index()
    {
        $id = XcRequestUtils::get('id', true);
        $dao = new \app\admin\model\csmwj\Userpaper();
        // 数据概况 - 有效工单总数
        $totalCount = null;
        if (true) {
            $totalCount = $dao->where('csmwj_paper_id', '=', $id)
                ->where('status', '=', 'normal')
                ->where('iseffectverison', '=', 'Y')
                ->where('answerstatus', '=', 'FINISH')
                ->count();
        }
        // 数据概况 - 今日新增工单
        $todayCount = null;
        if (true) {
            $todayLastSeconds = mktime(23, 59, 59, date('m'), date('d'), date('Y'));
            $todayFirstSeconds = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
            $todayCount = $dao->where('csmwj_paper_id', '=', $id)
                ->where('status', '=', 'normal')
                ->where('iseffectverison', '=', 'Y')
                ->where('answerstatus', '=', 'FINISH')
                ->where('createtime', '>', $todayLastSeconds)
                ->where('createtime', '<', $todayFirstSeconds)
                ->count();
        }
        // 数据概况 - 平均答题时长
        $avgAnswerSecs = 0;
        if ($totalCount > 0) {
            $totalUsedsecond = $dao->where('csmwj_paper_id', '=', $id)
                ->where('status', '=', 'normal')
                ->where('iseffectverison', '=', 'Y')
                ->where('answerstatus', '=', 'FINISH')
                ->sum("usedsecond");
            $avgAnswerSecs = (int)($totalUsedsecond / $totalCount);
        }
        // 数据概况 - 总访问人数
        $totalUserCount = null;
        if (true) {
            $totalUserCount = $dao->where('csmwj_paper_id', '=', $id)
                ->where('status', '=', 'normal')
                ->where('iseffectverison', '=', 'Y')
                ->where('answerstatus', '=', 'FINISH')
                ->count('distinct csmwj_weixinuser_id');
        }
        // 数据概况 - 总完成率
        $totalFinishPercent = 0;
        if ($totalUserCount > 0) {
            $totalFinishPercent = $totalCount * 100 / $totalUserCount;
        }

        $this->view->assign("totalCount", $totalCount);
        $this->view->assign("todayCount", $todayCount);
        $this->view->assign("avgAnswerSecs", $avgAnswerSecs);
        $this->view->assign("totalUserCount", $totalUserCount);
        $this->view->assign("totalFinishPercent", $totalFinishPercent);


        $province = db('rui_province')->column('id,name');
        $this->view->assign('province', $province);

        $company = db('rui_company')->column('id,name');
        $this->view->assign('company', $company);

        //配件使用率
        $id1 = db('csmwj_userpaper')
            ->where('status', 'normal')
            ->where('answerstatus', '=', 'FINISH')
            ->where('csmwj_paper_id', 13)
            ->order('id desc')
            ->column('id');

//        $genghuanpeijian = 15;
//        $guzhangpeijianpingpai = 80;
//        $genghuanshuliang = 81;
        $array = [];
        foreach ($id1 as $v) {
            $list = db('csmwj_userquestion')
                ->where('csmwj_userpaper_id', $v)
                ->where('csmwj_question_id', 'in', [15, 80, 81])
                ->field('csmwj_question_id,answer')
                ->select();
            $a1 = 0;
            $a2 = 0;
            $a3 = 0;
            //一次的提交记录
            foreach ($list as $k2 => $v2) {
                if ($v2['csmwj_question_id'] == 15) {
                    $a1 = json_decode($v2['answer'], 1)['value'];
                }

                if ($v2['csmwj_question_id'] == 80) {
                    $a2 = json_decode($v2['answer'], 1)['value'];
                }

                if ($v2['csmwj_question_id'] == 81) {
                    $a3 = json_decode($v2['answer'], 1)['value'];
                }
            }
            if (!empty($a1) and !empty($a2) and !empty($a3)) {
                $qq['peijian'] = $a1 . '-' . $a2;
                $qq['shuliang'] = $a3;
                $array[] = $qq;
            }

        }

        foreach ($array as $item) {
            $peijian = $item['peijian'];
            $shuliang = $item['shuliang'];
            if (isset($accumulated[$peijian])) {
                $accumulated[$peijian] += $shuliang;
            } else {
                $accumulated[$peijian] = $shuliang;
            }
        }

        $result = [];
        foreach ($accumulated as $peijian => $shuliang) {
            $result[] = ['peijian' => $peijian, 'shuliang' => $shuliang];
        }

        usort($result, function ($a, $b) {
            return $b['shuliang'] - $a['shuliang'];
        });
        // 输出结果
        //print_r($result);die;

        $this->view->assign("result", $result);

        return $this->view->fetch();
    }

    public function index2()
    {

        $id = XcRequestUtils::get('id', true);
        $dao = new \app\admin\model\csmwj\Userpaper();
        // 数据概况 - 有效工单总数
        $totalCount = null;
        if (true) {
            $totalCount = $dao->where('csmwj_paper_id', '=', $id)
                ->where('status', '=', 'normal')
                ->where('iseffectverison', '=', 'Y')
                ->where('answerstatus', '=', 'FINISH')
                ->count();
        }
        // 数据概况 - 今日新增工单
        $todayCount = null;
        if (true) {
            $todayLastSeconds = mktime(23, 59, 59, date('m'), date('d'), date('Y'));
            $todayFirstSeconds = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
            $todayCount = $dao->where('csmwj_paper_id', '=', $id)
                ->where('status', '=', 'normal')
                ->where('iseffectverison', '=', 'Y')
                ->where('answerstatus', '=', 'FINISH')
                ->where('createtime', '>', $todayLastSeconds)
                ->where('createtime', '<', $todayFirstSeconds)
                ->count();
        }
        // 数据概况 - 平均答题时长
        $avgAnswerSecs = 0;
        if ($totalCount > 0) {
            $totalUsedsecond = $dao->where('csmwj_paper_id', '=', $id)
                ->where('status', '=', 'normal')
                ->where('iseffectverison', '=', 'Y')
                ->where('answerstatus', '=', 'FINISH')
                ->sum("usedsecond");
            $avgAnswerSecs = (int)($totalUsedsecond / $totalCount);
        }
        // 数据概况 - 总访问人数
        $totalUserCount = null;
        if (true) {
            $totalUserCount = $dao->where('csmwj_paper_id', '=', $id)
                ->where('status', '=', 'normal')
                ->where('iseffectverison', '=', 'Y')
                ->where('answerstatus', '=', 'FINISH')
                ->count('distinct csmwj_weixinuser_id');
        }
        // 数据概况 - 总完成率
        $totalFinishPercent = 0;
        if ($totalUserCount > 0) {
            $totalFinishPercent = $totalCount * 100 / $totalUserCount;
        }

        $this->view->assign("totalCount", $totalCount);
        $this->view->assign("todayCount", $todayCount);
        $this->view->assign("avgAnswerSecs", $avgAnswerSecs);
        $this->view->assign("totalUserCount", $totalUserCount);
        $this->view->assign("totalFinishPercent", $totalFinishPercent);
        return $this->view->fetch();
    }

    // 数据概况 e 现状图数据
    public function index_ajax_trend()
    {
        $id = XcRequestUtils::get("id", true);
        $begin = XcRequestUtils::get("begin", true);
        $end = XcRequestUtils::get("end", true);

        $begindate = strtotime($begin);
        $enddate = strtotime($end);
        $calcday = ($enddate - $begindate) / 24 / 3600;
        $line1 = [];
        for ($i = 0; $i <= $calcday; $i++) {
            $dd = date("Y-m-d", $begindate);
            $line1[$dd] = [
                $dd,
                0,
                0
            ];
            $begindate = $begindate + 3600 * 24;
        }

        $dao = new \app\admin\model\csmwj\Userpaper();

        if (true) {
            $list = $dao->where('csmwj_paper_id', '=', $id)
                ->where('status', '=', 'normal')
                ->where('iseffectverison', '=', 'Y')
                ->where('answerstatus', '=', 'FINISH')
                ->where("statdate", ">=", $begin)
                ->where("statdate", "<=", $end)
                ->field('statdate,count(distinct csmwj_weixinuser_id) cnt')
                ->group('statdate')
                ->select();
            foreach ($list as $v) {
                $line1[$v->statdate][1] = $v->cnt;
            }
        }
        if (true) {
            $list = $dao->where('csmwj_paper_id', '=', $id)
                ->where('status', '=', 'normal')
                ->where('iseffectverison', '=', 'Y')
                ->where('answerstatus', '=', 'FINISH')
                ->where("statdate", ">=", $begin)
                ->where("statdate", "<=", $end)
                ->field('statdate,count(*) cnt')
                ->group('statdate')
                ->select();
            foreach ($list as $v) {
                $line1[$v->statdate][2] = $v->cnt;
            }
        }

        $this->success("", null, array(
            "line1" => $this->adjust($line1, [
                'product',
                '有效工单数',
                '访问人数'
            ])
        ));
    }

    public function index_ajax_trend2()
    {

    }

    // 成绩概况
    public function score()
    {
        $id = XcRequestUtils::get('id', true);
        $dao = new \app\admin\model\csmwj\Userpaper();

        // 数据概况 - 有效工单总数
        $totalCount = null;
        if (true) {
            $totalCount = $dao->where('csmwj_paper_id', '=', $id)
                ->where('status', '=', 'normal')
                ->where('iseffectverison', '=', 'Y')
                ->where('answerstatus', '=', 'FINISH')
                ->count();
        }
        // 成绩概况 - 平均分
        $avgScore = 0;
        if ($totalCount > 0) {
            $totalScore = $dao->where('csmwj_paper_id', '=', $id)
                ->where('status', '=', 'normal')
                ->where('iseffectverison', '=', 'Y')
                ->where('answerstatus', '=', 'FINISH')
                ->sum("score");
            $avgScore = (int)$totalScore / $totalCount;
        }
        // 成绩概况 - 最高分
        $maxScore = 0;
        if ($totalCount > 0) {
            $maxScore = $dao->where('csmwj_paper_id', '=', $id)
                ->where('status', '=', 'normal')
                ->where('iseffectverison', '=', 'Y')
                ->where('answerstatus', '=', 'FINISH')
                ->max("score");
        }
        // 成绩概况 - 最低分
        $minScore = 0;
        if ($totalCount > 0) {
            $minScore = $dao->where('csmwj_paper_id', '=', $id)
                ->where('status', '=', 'normal')
                ->where('iseffectverison', '=', 'Y')
                ->where('answerstatus', '=', 'FINISH')
                ->min("score");
        }

        $this->view->assign("baseurl", $this->request->baseUrl());
        $this->view->assign("avgScore", $avgScore);
        $this->view->assign("maxScore", $maxScore);
        $this->view->assign("minScore", $minScore);
        return $this->view->fetch();
    }

    // 统计工单
    public function paperdetail()
    {
        $id = XcRequestUtils::get('id', true);

        $paper = null;
        if (true) {
            $dao = new \app\admin\model\csmwj\Paper();
            $paper = $dao->where('id', '=', $id)
                ->field('id,name')
                ->find();
        }

        $questions = null;
        if (true) {
            $dao = new \app\admin\model\csmwj\Question();
            $questions = $dao->where('csmwj_paper_id', '=', $id)
                ->where('status', '=', 'normal')
                ->where('fieldtag', 'not in', [
                    'question-header',
                    'question-footer',
                    'question-bodytext'
                ])
                ->field('id,title,fieldtag')
                ->order('weigh', 'desc')
                ->select();
        }

        $answers = null;
        if (true) {
            $dao = new \app\admin\model\csmwj\Userpaper();
            $answers = $dao->alias('t')
                ->join('csmwj_userquestion a', 't.id=a.csmwj_userpaper_id')
                ->field('a.csmwj_question_id,a.answer')
                ->where('csmwj_paper_id', '=', $id)
                ->where('iseffectverison', '=', 'Y')
                ->where('answerstatus', '=', 'FINISH')
                ->select();
        }

        // 将答案汇总到answer中
        if (true) {
            foreach ($questions as $k => $item) {
                $aa = [];
                $cc = 0; // 总次数
                foreach ($answers as $item2) {
                    $answerjson = json_decode($item2->answer, true);
                    if ($item->id == $item2->csmwj_question_id) {
                        switch ($item->fieldtag) {
                            case "question-input":
                                $cc++;
                                $aa[$answerjson['value']] = isset($aa[$answerjson['value']]) ? $aa[$answerjson['value']] + 1 : 1;
                                break;
                            case "question-radio-group":
                            case "question-select-group":
                                $cc++;
                                $aa[$answerjson['value']] = isset($aa[$answerjson['value']]) ? $aa[$answerjson['value']] + 1 : 1;
                                break;
                            case "question-checkbox-group":
                                foreach ($answerjson['value'] as $jj) {
                                    $cc++;
                                    $aa[$jj] = isset($aa[$jj]) ? $aa[$jj] + 1 : 1;
                                }
                                break;
                        }
                    }
                }

                // $value=>$cnt 改为 {value:$value,cnt:$cnt,percent:10%}
                $aa2 = [];
                $ii = 0;
                foreach ($aa as $k2 => $v2) {
                    $aa2[] = [
                        'no' => ++$ii,
                        'value' => $k2,
                        'cnt' => $v2,
                        'percent' => (int)($v2 * 100 / $cc)
                    ];
                }

                $questions[$k]->answers = $aa2;
            }
        }

        $this->view->assign("paper", $paper);
        $this->view->assign("questions", $questions);
        return $this->view->fetch();
    }

    // 显示回答的list详情页面
    public function answerlist2()
    {
        $id = XcRequestUtils::get('id', true);
        $info = db('csmwj_userpaper')->where('id', $id)->find();
        $id = $info['csmwj_paper_id'];
        $qid = $info['id'];
        $paper = null;
        if (true) {
            $dao = new \app\admin\model\csmwj\Paper();
            $paper = $dao->where('id', '=', $id)
                ->field('id,name')
                ->find();
        }

        $columns = null;
        if (true) {
            $dao = new \app\admin\model\csmwj\Question();
            $columns = $dao->where('csmwj_paper_id', '=', $id)
                ->where('status', '=', 'normal')
                ->where('csmtype', 'not in', [
                    'question-header',
                    'question-footer',
                    'question-bodytext'
                ])
                ->field('id,id field,title')
                ->order('weigh', 'desc')
                ->select();
        }

        if ($this->request->isAjax()) {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            /**
             * 按照columns格式读取useranswer
             *
             * spa. 读取该工单所有有效的回答
             * spb. 读取该回答的所有answer list
             * spb-1. 按照column转换,记录数为userpaper/useranswer list->row
             */
            $list = [];
            $userpapers = null;
            if (true) {
                // spa
                $dao = new \app\admin\model\csmwj\Userpaper();
                $userpapers = $dao->where('csmwj_paper_id', '=', $id)
                    ->where('id', $qid)
                    ->where('status', '=', 'normal')
                    ->where('answerstatus', '=', 'FINISH')
                    ->order('createtime', 'desc')
                    ->order($sort, $order)
                    ->paginate($limit);

                $dao_useranswer = new \app\admin\model\csmwj\Userquestion();
                foreach ($userpapers as $item) {
                    $tt = [
                        'id' => $item->id,
                        'submitmethod' => __('submitmethod ' . $item->submitmethod),
                        'usedsecond' => $item->usedsecond,
                        'score' => $item->score,
                        'createtime' => $item->createtime,
                        'image' => $item->image
                    ];

                    // spb.
                    $useranswers = $dao_useranswer->alias('t')
                        ->join('csmwj_question a', 't.csmwj_question_id=a.id')
                        ->field('t.answer,t.csmwj_question_id,a.fieldtag,a.csmtype')
                        ->where('t.csmwj_userpaper_id', '=', $item->id)
                        ->where('t.status', '=', 'normal')
                        ->select();
                    // spb-1.
                    foreach ($useranswers as $item2) {

                        $json = json_decode($item2->answer, true);
                        $val = '';
                        switch ($item2->csmtype) {
                            case "question-input":
                                $val = $json['value'];
                                break;
                            case "question-radio-group":
                            case "question-select-group":
                                $val = $json['value'];
                                break;
                            case "question-checkbox-group":
                            case "question-score":
                                foreach ($json['value'] as $jj) {
                                    $val .= ' ' . $jj;
                                }
                                break;
                        }
                        $tt['f_' . $item2->csmwj_question_id] = $val;
                    }
                    $list[] = $tt;
                }
            }

            $result = array(
                "total" => $userpapers->total(),
                "rows" => $list,
                'columns' => $columns
            );

            return json($result);
        }

        $this->assignconfig('columns', $columns);
        return $this->view->fetch('answerlist2');
    }

    // 显示回答的list详情页面
    public function answerlist()
    {
        $id = XcRequestUtils::get('id', true);
        $paper = null;
        if (true) {
            $dao = new \app\admin\model\csmwj\Paper();
            $paper = $dao->where('id', '=', $id)
                ->field('id,name')
                ->find();
        }

        $columns = null;
        if (true) {
            $dao = new \app\admin\model\csmwj\Question();
            $columns = $dao->where('csmwj_paper_id', '=', $id)
                ->where('status', '=', 'normal')
                ->where('csmtype', 'not in', [
                    'question-header',
                    'question-footer',
                    'question-bodytext'
                ])
                ->field('id,id field,title')
                ->order('weigh', 'desc')
                ->select();
        }

        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            /**
             * 按照columns格式读取useranswer
             *
             * spa. 读取该工单所有有效的回答
             * spb. 读取该回答的所有answer list
             * spb-1. 按照column转换,记录数为userpaper/useranswer list->row
             */
            $list = [];
            $userpapers = null;
            if (true) {
                // spa
                $dao = new \app\admin\model\csmwj\Userpaper();
                $userpapers = $dao->where('csmwj_paper_id', '=', $id)
                    ->where('status', '=', 'normal')
                    ->where('iseffectverison', '=', 'Y')
                    ->where('answerstatus', '=', 'FINISH')
                    ->order('createtime', 'desc')
                    ->order($sort, $order)
                    ->paginate($limit);

                $dao_useranswer = new \app\admin\model\csmwj\Userquestion();
                foreach ($userpapers as $item) {
                    $tt = [
                        'id' => $item->id,
                        'submitmethod' => __('submitmethod ' . $item->submitmethod),
                        'usedsecond' => $item->usedsecond,
                        'score' => $item->score,
                        'createtime' => $item->createtime
                    ];

                    // spb.
                    $useranswers = $dao_useranswer->alias('t')
                        ->join('csmwj_question a', 't.csmwj_question_id=a.id')
                        ->field('t.answer,t.csmwj_question_id,a.fieldtag,a.csmtype')
                        ->where('t.csmwj_userpaper_id', '=', $item->id)
                        ->where('t.status', '=', 'normal')
                        ->select();
                    // spb-1.
                    foreach ($useranswers as $item2) {
                        $json = json_decode($item2->answer, true);
                        $val = '';
                        switch ($item2->csmtype) {
                            case "question-input":
                                $val = $json['value'];
                                break;
                            case "question-radio-group":
                            case "question-select-group":
                                $val = $json['value'];
                                break;
                            case "question-checkbox-group":
                            case "question-score":
                                foreach ($json['value'] as $jj) {
                                    $val .= ' ' . $jj;
                                }
                                break;
                        }
                        $tt['f_' . $item2->csmwj_question_id] = $val;
                    }
                    $list[] = $tt;
                }
            }

            $result = array(
                "total" => $userpapers->total(),
                "rows" => $list,
                'columns' => $columns
            );

            return json($result);
        }
        $this->assignconfig('columns', $columns);
        return $this->view->fetch('answerlist');
    }

    private function adjust($list, $lables)
    {
        $ll = [];
        foreach ($list as $v) {
            $ll[] = $v;
        }
        array_unshift($ll, $lables);
        return $ll;
    }


    //添加
    public function add()
    {
        return;
    }

    //编辑
    public function edit($ids = null)
    {
        return;
    }

    //删除
    public function del($ids = null)
    {
        return;
    }

    //回收站列表
    public function recyclebin()
    {
        return;
    }

    //回收站(真实删除或清空)
    public function destroy($ids = null)
    {
        return;
    }

    //回收站还原
    public function restore($ids = null)
    {
        return;
    }

    //批量操作(修改状态)
    public function multi($ids = null)
    {
        return;
    }
}
